class StudentsController < ApplicationController
    # login_required only on new and create because it is overkill for others
    before_filter :login_required, :only => [:new, :create]
    before_filter :student_required, :except => [:index, :destroy, :new, :create]
    before_filter :admin_required, :only => [:index, :destroy]
    before_filter :ownership_required, :except => [:index, :new, :create]

  def index
      @students = Student.find(:all)
  end

  def show
      # @student comes from :require_ownership filter
  end

  def new
      @student = Student.new
      @student.username = current_user.login
      @student.user_id = current_user.id
  end

  def create
      @student = Student.new(params[:student])
      dg = DegreeRequirement.find_by_is_default(true)
      @student.degree_requirement_id = dg.id
      if @student.save
          @plan = Plan.new
          @plan.status = DRAFT
          @plan.student_id = @student.id
          @plan.save(false)
          flash[:notice] = "Student saved successfully"
          redirect_to(plans_url)
      else
          render :action => "new"
      end
  end

  def edit
      # @student from require_ownership filter
  end

  def update
      # @student comes from require_ownership filter
      if @student.update_attributes(params[:student])
          flash[:notice] = "Student updated successfully"
          redirect_to(@student)
      else
          render :action => "edit"
      end
  end

  def destroy
      # @student comes from require_ownership filter
      @student.destroy
      redirect_to(students_url)
  end

  private

    def ownership_required
        @student = Student.find(params[:id])
        if current_user.role == "administrator"
            return true
        end
        if current_student == @student
            return true
        else
            redirect_to(PermissionDeniedURL)
        end
    end

end
